<?php
/**
 *
 * @author Strawberry🍓
 * @date 2021-05-21 4:08 下午
 *
 */

namespace app\common\model\tang;


use app\common\impl\Comm;
use app\common\model\CommonBaseModel;
use app\common\model\tang\CostRule;
use think\facade\Db;
use PHPExcel_IOFactory;

class Cost extends CommonBaseModel implements Comm
{

    public function getAdminPageData($param = [], $order = 'id desc',$where =[],$with=[])
    {
        $model = self::where($where);
        if (isset($param['merchant_id']) && $param['merchant_id']){
            $model->where('merchant_id','=',$param['merchant_id']);
        }
        if (isset($param['is_void']) && $param['is_void']){
            $model->where('is_void','=',$param['is_void']);
        }
        if (isset($param['invoice']) && $param['invoice']!=''){
            $model->where('invoice','=',$param['invoice']);
        }
        if(!isset($where['pay_status'])){
            $model->where('pay_status','>',-2);
        }
        if(isset($param['pointId']) && $param['pointId']){
            $model->where('pointId','like',"%{$param['pointId']}%");
        }
        if(isset($param['settlement_time']) && $param['settlement_time']){
            $model->where('settlement_time','=',$param['settlement_time']);
        }
        if (isset($param['mobile']) && $param['mobile']){
            $model->where('mobile','like',"%{$param['mobile']}%");
        }
        if (isset($param['contract_code']) && $param['contract_code']){

            $model->where('contract_code','like',"%{$param['contract_code']}%");
        }
        if (isset($param['cost_type_id']) && $param['cost_type_id']){
            $model->where('cost_type_id','=',$param['cost_type_id']);
        }
        if (isset($param['billNubmer']) && $param['billNubmer']){
//            $model->where('billNubmer','=',$param['billNubmer']);
            $model->where('billNubmer','like',"%{$param['billNubmer']}%");
        }
        if (isset($param['order_sn']) && $param['order_sn']){
            $model->where('order_sn','like',"%{$param['order_sn']}%");
        }
        if (isset($param['pay_status']) && $param['pay_status']!=null ){
            $model->where('pay_status','=',$param['pay_status']);
        }
        if(isset($param['time'])&&$param['time']){
            $endtime = strtotime('-'.$param['time'].' day');
            $model->whereBetweenTime('create_time','<',$endtime);
            $model->where('pay_status','=',0);
        }
        // TODO: Implement getAdminPageData() method.
        $data = $model->with(['merchant','costType','watchInfo'])->order($order)->page(PAGE)->limit(LIMIT)->select()->toArray();
        $count = $model->count("id");
        if($data){
            foreach ($data as&$v){
                $v['frequency'] = (new SendConfigLog())->where('cost_id',$v['id'])->count();
//                if($v['merchant']['username']=='-'||empty($v['merchant']['username'])){
//                    $v['merchant']['username'] = $v['merchant']['company'];
//                }
                  if($v['is_admin_create']==0 || $v['is_user']==0){  // 人工创建
                        $v['fname']  = $v['costType']['cost_name'] ;
                  }else{ // 自主创建
                        switch ($v['cost_type_id']){
                            case 1 :
                                $v['fname'] = '电费' ;
                                break ;
                            case 2 :
                                $v['fname'] = '水费' ;
                                break ;
                        }
                  }
            }
        }
        return parent::ajaxResult($data, $count);
    }
    public function getExportPageData($param,$order='id desc',$where=[]){
        $model = self::where($where);
        if (isset($param['merchant_id']) && $param['merchant_id']){
            $model->where('merchant_id','=',$param['merchant_id']);
        }
        if(!isset($where['pay_status'])){
            $model->where('pay_status','>',-2);
        }
        if(isset($param['pointId']) && $param['pointId']){
            $model->where('pointId','like',"%{$param['pointId']}%");
        }
        if (isset($param['contract_code']) && $param['contract_code']){
            $model->where('contract_code','like',"%{$param['contract_code']}%");
        }
        if (isset($param['settlement_time']) && $param['settlement_time']){
            $model->where('settlement_time','=',$param['settlement_time']);
        }
        if (isset($param['pay_status']) && $param['pay_status']!=null ){
            $model->where('pay_status','=',$param['pay_status']);
        }
        if(isset($param['time'])&&$param['time']){
            $endtime = strtotime('-'.$param['time'].' day');
            $model->whereBetweenTime('create_time','<',$endtime);
            $model->where('pay_status','=',0);
        }
        $data = $model->with(['merchant','costType'])->order($order)->select()->toArray();
        $export = [];
        if($where['type']==5){
            $title = ['商户名','商户编号','合同号','表号','实际用量','合计(元)','结算期','缴费状态','缴费时间'];
            foreach ($data as $key => $value) {
                if($value['merchant']['name']=='-'||empty($value['merchant']['name'])){
                    $merchant_name = $value['merchant']['company'];
                }else{
                    $merchant_name = $value['merchant']['name'];
                }
                if($value['pay_status']==0){
                    $pay_status = '未支付';
                }else{
                    $pay_status = '已支付';
                }
                $export[$key]['merchant_name'] =$merchant_name;
                $export[$key]['merchant_sn'] ="\t".$value['merchant']['merchant_sn']."\t";
                $export[$key]['code'] =  "\t".$value['merchant']['code']."\t";
                $export[$key]['pointId'] =  "\t".$value['pointId']."\t";
                $export[$key]['use_number'] = $value['use_number'];
                $export[$key]['all_amount'] = $value['all_amount']/100;
                $export[$key]['settlement_time'] = $value['settlement_time'];
                $export[$key]['pay_status'] = $pay_status;
                $export[$key]['pay_time'] = $value['pay_time'];
            }
            return export_excel('水费账单_'.date('Y-m-d'),$title,$export);
        }else{
            $title = ['商户名','商户编号','合同号','表号','电费(元)','服务费(元)','合计(元)','结算期','缴费状态','缴费时间'];
            foreach ($data as $key => $value) {
                if($value['merchant']['name']=='-'||empty($value['merchant']['name'])){
                    $merchant_name = $value['merchant']['company'];
                }else{
                    $merchant_name = $value['merchant']['name'];
                }
                if($value['pay_status']==0){
                    $pay_status = '未支付';
                }else{
                    $pay_status = '已支付';
                }
                $export[$key]['merchant_name'] =$merchant_name;
                $export[$key]['merchant_sn'] ="\t".$value['merchant']['merchant_sn']."\t";
                $export[$key]['code'] =  "\t".$value['merchant']['code']."\t";
                $export[$key]['pointId'] =  "\t".$value['pointId']."\t";
                $export[$key]['electric_money'] = $value['electric_money']/100;
                $export[$key]['fuwu_money'] =$value['fuwu_money']/100;
                $export[$key]['all_amount'] = $value['all_amount']/100;
                $export[$key]['settlement_time'] = $value['settlement_time'];
                $export[$key]['pay_status'] = $pay_status;
                $export[$key]['pay_time'] = $value['pay_time'];
            }
            return export_excel('电费账单_'.date('Y-m-d'),$title,$export);
        }


    }
    public function getExportData($param,$order='id desc',$where=[]){
        $model = self::where($where);
        if (isset($param['merchant_id']) && $param['merchant_id']){
            $model->where('merchant_id','=',$param['merchant_id']);
        }
//        if(!isset($where['pay_status'])){
//            $model->where('pay_status','>',-2);
//        }
        if (isset($param['contract_code']) && $param['contract_code']){
            $model->where('contract_code','like',"%{$param['contract_code']}%");
        }
        if (isset($param['order_sn']) && $param['order_sn']){
            $model->where('order_sn','like',"%{$param['order_sn']}%");
        }
        if (isset($param['pay_status']) && $param['pay_status']!=null ){
            $model->where('pay_status','=',$param['pay_status']);
        }
        if (isset($param['cost_type_id']) && $param['cost_type_id']!=null ){
            $model->where('cost_type_id','=',$param['cost_type_id']);
        }
        $data = $model->with(['merchant','costType'])->order($order)->select()->toArray();
        $export = [];
        $title = ['商户名','商户编号','合同号','缴费单编号','海鼎账单号','费用项','待缴金额','实收金额(元)','账单金额(元)','缴费区间','缴费状态','缴费时间'];
        foreach ($data as $key => $value) {
            if($value['merchant']['name']=='-'||empty($value['merchant']['name'])){
                $merchant_name = $value['merchant']['company'];
            }else{
                $merchant_name = $value['merchant']['name'];
            }
            if($value['pay_status']==0){
                $pay_status = '未支付';
            }else{
                $pay_status = '已支付';
            }
            $export[$key]['merchant_name'] =$merchant_name;
            $export[$key]['merchant_sn'] ="\t".$value['merchant']['merchant_sn']."\t";
            $export[$key]['code'] =  "\t".$value['merchant']['code']."\t";
            $export[$key]['order_sn'] =  "\t".$value['order_sn']."\t";
            $export[$key]['billNubmer'] =  "\t".$value['billNubmer']."\t";
            $export[$key]['cost_type_id'] =  "\t".$value['costType']['cost_name']."\t";
            $export[$key]['amount'] =  $value['amount']/100;
            $export[$key]['pay_amount'] = $value['pay_amount']/100;
            $export[$key]['all_amount'] = $value['all_amount']/100;
            $export[$key]['time'] = date('Y-m-d',$value['start_time']).'~'.date('Y-m-d',$value['end_time']);
            $export[$key]['pay_status'] = $pay_status;
            $export[$key]['pay_time'] = $value['pay_time'];
        }
        return export_excel('商户费用_'.date('Y-m-d'),$title,$export);
    }
    public function delById($ids)
    {
        Db::startTrans();
        try {
            if (is_array($ids)){
                $id=$ids;
            }else{
                $id=@explode(",",$ids);
            }
            $result = self::where('id', 'in',$id)->delete();
            Db::commit();
            if ($result) {
                $CostRulelist = (new CostRule())->where('pid', 'in',$id)->select();
                if(!empty($CostRulelist)){
                    $res = (new CostRule())->where('pid', 'in',$id)->delete();
                }
                return self::JsonReturn("删除成功");
            } else {
                return self::JsonReturn("删除失败",0);
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return self::JsonReturn($exception->getMessage(),0);
        }
        // TODO: Implement delById() method.
    }


    public function doAll($data)
    {
        // TODO: Implement doAll() method.
        return parent::doAllData($data);
    }
    public function merchant(): \think\model\relation\HasOne
    {
        return $this->hasOne(Merchant::class,'id','merchant_id');
    }
    public function costType(): \think\model\relation\HasOne
    {
        return $this->hasOne(CostType::class,'id','cost_type_id');
    }

    public function merchants()
    {
        return $this->hasOne(Merchant::class,'id','merchant_id');
    }

    public function costRule()
    {
        return $this->hasMany(CostRule::class,'pid','id');
    }

    public function costRules()
    {
        $m = $this->hasMany(CostRule::class,'pid','id') ;
        return  $m = $m->with('costType') ;
    }

    public function subjectList()
    {
        return $this->hasOne(SubjectList::class,'id','department_id');
    }
    public function payType()
    {
        return $this->hasOne(SubjectList::class,'id','subject_id');
    }
    public function Cost()
    {
        return $this->hasMany(Cost::class,'pid','id');
    }
    public function sectionCost()
    {
        return $this->hasOne(CostSectionPay::class,'cost_id','id');
    }
    public function watchInfo(){
        return $this->hasOne(WatchMaintain::class,'pointId','pointId');
    }
    public function ticketConfig(){
        return $this->hasOne(TicketConfig::class,'id','ticket_id');
    }
}